package org.ft.handler;

import org.ft.dao.UserDao;
import org.jasig.cas.authentication.HandlerResult;
import org.jasig.cas.authentication.PreventedException;
import org.jasig.cas.authentication.UsernamePasswordCredential;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.StringUtils;

import javax.security.auth.login.AccountException;
import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.FailedLoginException;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义登陆验证
 * Created by Chen Tianzhong in 2022/3/9
 */
public class UsersAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {

    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException {
        String username=credential.getUsername();
        String password=credential.getPassword();
        if(StringUtils.isEmpty(username)){
            throw new AccountNotFoundException("用户名称不能为空");
        }
        if (!username.contains("@gxfy.com")){
            username = username+"@gxfy.com";
        }

        System.out.println("username=["+username+"]  password=["+password+"]");


        Map<String, Object> map = userDao.findMapByUsername(username);
        if (map==null || map.isEmpty()){
            throw new AccountNotFoundException("用户不存在");
        }
        return  createHandlerResult(credential,new SimplePrincipal(username),null);

    }

}
